<template>
  <div class="wrap" v-loading="pageLoading">
    <div class="header-btn">
      <div>{{ title }}</div>
      <div>
        <el-button type="primary" @click="submit" v-if="type !== 'detail'">确认</el-button>
        <el-button type="info" plain @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="g-card" style="padding-bottom: 16px">
      <div class="title-header">基础设置</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="right"
        style="position: relative">
        <el-form-item label="旅程名称" prop="flowName">
          <el-input v-show="!fromDetail" v-model="form.flowName" popper-class="minWidth-inp" style="width: 400px"
            placeholder="请输入" maxlength="32">
          </el-input>
          <div v-show="fromDetail">{{ form.flowName }}</div>
        </el-form-item>
        <el-form-item label="触发条件" prop="triggerId">
          <el-radio-group :value="form.triggerId" v-show="!fromDetail" @input="radioChange">
            <el-radio :label="item.dictValue" v-for="item in radioGroup" :key="item.dictValue">{{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
          <div v-show="fromDetail">{{ form.triggerName }}</div>
        </el-form-item>
      </el-form>
    </div>
    <div class="g-card">
      <div class="title-header">用户旅程阶段</div>
      <div class="options-btn" v-if="!optionsFlag">
        <el-button type="primary" @click="addFlag = true" style="margin-left: 20px"
          icon="el-icon-circle-plus-outline">创建</el-button>
      </div>
      <div class="options-flex">
        <div class="options-list" v-for="(item, index) in journeyFlowNodeList" :key="index">
          <div class="options-item" :style="{
            'background-color': selectIndex === index ? '#082aff' : '#FC876A',
          }" @click="showJourneyItem(item, index)">

            <div class="options-des">
              {{ item.scrmJourneyFlowNodeInfolist.length >= 1 ? item.scrmJourneyFlowNodeInfolist[0].value : "" }}
              {{
                item.scrmJourneyFlowNodeInfolist.length >= 2 && item.scrmJourneyFlowNodeInfolist[1].nameNg !==
                'articleLink' ? " - " + item.scrmJourneyFlowNodeInfolist[1].value : ""
              }}
            </div>
            <div class="options-box">
              {{ item.flowNodeName }}
            </div>
          </div>
          <div class="options-group">
            <el-popover placement="top" width="130" trigger="hover" :disabled="!addFlag">
              <svg-icon icon-class="bgc-add" class="add-icon" v-show="!fromDetail" @click="handleAddJourneyItem(index)"
                slot="reference"></svg-icon>
              <div class="popover-text">请先确认当前选中旅程才可以创建哦！</div>
            </el-popover>
            <svg-icon icon-class="bgc-delete" class="delete-icon" v-show="!fromDetail" @click="deleteoptions(index)">
            </svg-icon>
            <div class="options-line"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="g-card" style="padding-bottom: 16px" v-if="addFlag">
      <div class="title-header options-btn" style="display: flex; justify-content: space-between">
        <div>用户旅程阶段配置</div>
        <div>
          <el-button type="primary" @click="submitOption" v-if="type !== 'detail'">确认</el-button>
        </div>
      </div>
      <el-form ref="options" :model="options" :rules="rules" label-width="120px" label-position="right"
        style="position: relative">
        <el-form-item label="阶段名称" prop="stageName">
          <el-input v-show="!fromDetail" v-model="options.stageName" popper-class="minWidth-inp" style="width: 400px"
            placeholder="请输入" maxlength="32">
          </el-input>
          <div v-show="fromDetail">{{ options.stageName }}</div>
        </el-form-item>
        <div v-if="form.triggerId === '8'" style="display: flex; justify-content: flex-start">
          <el-form-item label="消费金额区间" prop="consumptionMin">
            <el-input v-show="!fromDetail" v-model="options.consumptionMin" popper-class="minWidth-inp"
              style="width: 98px" placeholder="最低消费" @change="regNumber('consumptionMin', $event)">
            </el-input>
            <div v-show="fromDetail">{{ options.consumptionMin }}</div>
          </el-form-item>
          <span class="toline">-</span>
          <el-form-item label="" prop="consumptionMax" label-width="0">
            <el-input v-show="!fromDetail" v-model="options.consumptionMax" popper-class="minWidth-inp"
              style="width: 98px" placeholder="最高消费" @change="regNumber('consumptionMax', $event)">
            </el-input>
            <div v-show="fromDetail">{{ options.consumptionMax }}</div>
          </el-form-item>
        </div>
        <el-form-item label="指定日期" prop="date" v-if="form.triggerId === '6'">
          <el-date-picker :editable="false" v-model="options.date" v-show="!fromDetail" type="date" placeholder="指定日期"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd">
          </el-date-picker>
          <div v-show="fromDetail">{{ options.date }}</div>
        </el-form-item>
        <div v-if="form.triggerId === '9'" style="display: flex; justify-content: flex-start">
          <el-form-item label="按天次数区间" prop="dayMin">
            <el-input v-show="!fromDetail" v-model="options.dayMin" popper-class="minWidth-inp" style="width: 98px"
              placeholder="最低天数" @change="regNumber('dayMin', $event)">
            </el-input>
            <div v-show="fromDetail">{{ options.dayMin }}</div>
          </el-form-item>

          <span class="toline">-</span>
          <el-form-item label="" prop="dayMax" label-width="0">
            <el-input v-show="!fromDetail" v-model="options.dayMax" popper-class="minWidth-inp" style="width: 98px"
              placeholder="最高天数" @change="regNumber('daMax', $event)">
            </el-input>
            <div v-show="fromDetail">{{ options.dayMax }}</div>
          </el-form-item>
        </div>
        <div v-if="form.triggerId === '5'" style="display: flex; justify-content: flex-start">
          <el-form-item label="按次数区间" prop="frequencyMin">
            <el-input v-show="!fromDetail" v-model="options.frequencyMin" popper-class="minWidth-inp" style="width: 98px"
              placeholder="最低次数" @change="regNumber('frequencyMin', $event)">
            </el-input>
            <div v-show="fromDetail">{{ options.frequencyMin }}</div>
          </el-form-item>

          <span class="toline">-</span>
          <el-form-item label="" prop="frequencyMax" label-width="0">
            <el-input v-show="!fromDetail" v-model="options.frequencyMax" popper-class="minWidth-inp" style="width: 98px"
              placeholder="最高次数" @change="regNumber('frequencyMax', $event)">
            </el-input>
            <div v-show="fromDetail">{{ options.frequencyMax }}</div>
          </el-form-item>
        </div>
        <el-form-item label="选择文章" prop="name" v-if="form.triggerId === '7'">
          <!-- <el-input v-show="!fromDetail" v-model="options.name" popper-class="minWidth-inp" style="width: 400px"
            placeholder="请输入">
          </el-input> -->
          <el-button type="primary" icon="el-icon-plus" @click="articleVisible = true"
            v-if="!options.name">添加文章</el-button>
          <div v-else>
            {{ options.name }}
            <el-button type="text" @click="materialInfo()">详情</el-button>
            <el-button type="text" @click="deleteMaterial()" v-show="!fromDetail">删除</el-button>
          </div>
          <!-- <div v-show="fromDetail">{{ options.name }}</div> -->
        </el-form-item>
      </el-form>
    </div>
    <dialog-text text="修改条件后，您的已有内容将会被清除，是否确认修改？" :visible.sync="radioChangeVisible" @confirm="radioChangeConfirm">
    </dialog-text>
    <el-dialog title="选择文章" :visible.sync="articleVisible" width="50%" :modal="false">
      <material-article @confirm="selectMaterialConfrim" @view="preview"></material-article>
    </el-dialog>
    <Preview :content="previewContent" />
  </div>
</template>

<script>
import { nameValidate, onlyNumber } from "@/utils/validate";
import { selectDictLabel } from "@/utils/common";
import { JourneyFlowInfo, flowDetail } from "@/api/automarket/followStage";
import DialogText from "@/components/DialogText.vue";
import MaterialArticle from "./components/MaterialArticle";
import Preview from "@/components/Material/Preview";
export default {
  name: "AddFollowStage",
  components: {
    DialogText,
    MaterialArticle,
    Preview
  },
  data() {
    return {
      type: this.$route.query.type,
      articleVisible: false,
      title: "用户旅程配置",
      fromDetail: false,
      selectIndex: "", // 控制样式
      addIndex: "",    // 增加旅程位置
      addFlag: false,
      optionsFlag: false,
      journeyFlowNodeList: [],
      form: {
        flowName: "", // 旅程名称
        triggerId: "1", // 触发条件
        flowId: this.$route.query.flowId,
      },
      options: {
        stageName: "", // 阶段名称
        consumptionMin: "", // 消费金额区间
        consumptionMax: "",
        date: "", // 指定日期
        dayMin: "", // 最低天数
        dayMax: "", // 最高天数
        frequencyMin: "", // 最低次数
        frequencyMax: "", // 最高次数
        name: "", // 文章链接
        articleLink: "", // 文章链接
      },
      selectedList: [],
      rules: {
        triggerId: [
          {
            required: true,
            message: "请选择触发条件",
            trigger: "change",
          },
        ],
        stageName: [
          {
            required: true,
            validator: nameValidate("阶段"),
            trigger: "change",
          },
        ],
        consumptionMin: [
          {
            required: true,
            message: "请输入最低消费",
            trigger: "change",
          },
        ],
        consumptionMax: [
          {
            required: true,
            message: "请输入最高消费",
            trigger: "change",
          },
        ],
        date: [
          {
            required: true,
            message: "请选择指定日期",
            trigger: "change",
          },
        ],
        dayMin: [
          {
            required: true,
            message: "请输入最低天数",
            trigger: "change",
          },
        ],
        dayMax: [
          {
            required: true,
            message: "请输入最高天数",
            trigger: "change",
          },
        ],
        frequencyMin: [
          {
            required: true,
            message: "请输入最低次数",
            trigger: "change",
          },
        ],
        frequencyMax: [
          {
            required: true,
            message: "请输入最高次数",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请选择文章",
            trigger: "change",
          },
        ],
      },
      radioGroup: [],
      transToBack: {
        // 新添加好友，首次成交，沉默用户，客户生日
        // "1": {
        //   "stageName": "阶段名称",
        // },
        // "2": {
        //   "stageName": "阶段名称",
        // },
        // "3": {
        //   "stageName": "阶段名称",
        // },
        // "4": {
        //   "stageName": "阶段名称",
        // },
        // 消费金额区间
        "8": {
          "consumptionMin": "消费金额区间",
          "consumptionMax": "消费金额区间",
        },
        // 指定日期
        "6": {
          "date": "指定日期"
        },
        // 次数区间（按天）
        "9": {
          "dayMin": "按天次数区间",
          "dayMax": "按天次数区间"
        },
        // 次数区间（按次）
        "5": {
          "frequencyMin": "按次数区间",
          "frequencyMax": "按次数区间"
        },
        // 文章链接
        "7": {
          "name": "文章名称",
          "articleLink": "文章链接"
        }
      },
      pageLoading: false,
      radioChangeVisible: false,
      errText: {
        "5": "次数区间重复，请核实",
        "6": "指定日期重复，请核实",
        "7": "文章链接重复，请核实",
        "8": "消费金额区间重复，请核实",
        "9": "天数区间重复，请核实"
      },
      previewContent: {},
    };
  },

  watch: {
    journeyFlowNodeList: {
      immediate: true,
      handler() {
        if (this.journeyFlowNodeList.length) {
          this.optionsFlag = true;
        } else {
          this.optionsFlag = false;
        }
      }
    },
    selectedList: {
      deep: true,
      handler(newValue) {
        console.log(newValue, "newValue")
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    selectMaterialConfrim(selectMaterial) {
      this.options.articleLink = selectMaterial?.[0]?.id
      this.options.name = selectMaterial?.[0]?.materialName
      this.articleVisible = false
    },
    preview(item) {
      this.previewContent = item;
    },
    deleteMaterial() {
      this.options.articleLink = ""
      this.options.name = ""
    },
    materialInfo() {
      this.previewContent = {
        type: "article",
        id: this.options.articleLink,
      };
    },
    // 初始化
    async init() {
      this.pageLoading = true
      this.fromDetail = this.$route.query.type === "detail";
      try {
        // 触发条件
        let res = await this.getDicts("journey_condition_type")
        if (res.code === 200) {
          const temp = res.data
          if (this.$route.query.type !== "detail") {
            // 除查看详情外，不展示初始化单选按钮
            this.radioGroup = temp.filter(item => item.dictValue !== "10")
          } else {
            this.radioGroup = temp;
          }
        }
        if (this.form.flowId) {
          let res = await flowDetail(this.form.flowId)
          if (res.code === 200) {
            this.form.flowName = res.data.flowName;
            this.form.triggerId = res.data.triggerId + "";
            this.form.triggerName = selectDictLabel(this.radioGroup, res.data.triggerId)
            this.journeyFlowNodeList = res.data.journeyFlowNodeList;
          }
        }
        this.pageLoading = false
      } catch (error) {
        this.pageLoading = false
      }
    },
    radioChange(value) {
      if (this.journeyFlowNodeList.length > 0) {
        this.radioChangeVisible = true
        this.toChangeRadioValue = value
        return false
      } else {
        this.form.triggerId = value
      }
    },
    // 更换旅程触发条件
    radioChangeConfirm() {
      this.form.triggerId = this.toChangeRadioValue
      // 清空所有旅程阶段
      this.journeyFlowNodeList = []
      this.selectIndex = ""
      this.addIndex = ""
      if (this.addFlag) {
        this.resetJourneyConfig()
      }
      this.radioChangeVisible = false
    },
    showJourneyItem(item, index) {
      this.selectIndex = index
      this.addFlag = true
      item.scrmJourneyFlowNodeInfolist.forEach(element => {
        this.options[element.nameNg] = element.value
      })
      this.options.stageName = item.flowNodeName
    },
    handleAddJourneyItem(index) {
      // 选中用户旅程阶段时，不允许新增
      if (this.selectIndex !== "") return
      this.addIndex = index + 1
      this.addFlag = true
    },
    // 替换非数字
    regNumber(type, e) {
      this.options[`${type}`] = onlyNumber(e);
    },
    // 单次和相邻旅程大小比较
    numberCompare(minName, maxName) {
      let str = this.errText[this.form.triggerId] || "";
      if (minName === "consumptionMin") {
        str = "最高消费不得低于最低消费";
      } else if (minName === "dayMin") {
        str = "最高天数不得低于最低天数";
      } else if (minName === "frequencyMin") {
        str = "最高次数不得低于最低次数";
      } else {
        str = ""
      }
      if (+this.options[minName] > +this.options[maxName]) {
        this.$message.error(str);
        return false;
      }

      // 旅程区间校验
      const previousIndex = this.selectIndex === "" ? this.addIndex - 1 : this.selectIndex - 1
      const afterIndex = this.selectIndex === "" ? this.addIndex : this.selectIndex + 1
      if (this.journeyFlowNodeList?.[previousIndex] && +this.options[minName] <= +this.journeyFlowNodeList[previousIndex]?.scrmJourneyFlowNodeInfolist?.[1].value) {
        this.$message.error(this.errText[this.form.triggerId]);
        return false;
      }
      if (this.journeyFlowNodeList?.[afterIndex] && +this.options[maxName] >= +this.journeyFlowNodeList[afterIndex]?.scrmJourneyFlowNodeInfolist?.[0].value) {
        this.$message.error(this.errText[this.form.triggerId]);
        return false;
      }
      return true
    },
    // 用户旅程阶段配置确认
    submitOption() {
      // 消费金额区间
      this.$refs["options"].validate((valid) => {
        if (valid) {
          // 其他校验
          if (!this.otherValid()) return

          // 整理旅程配置后端数据
          let list = [];
          const configObject = this.transToBack[this.form.triggerId]
          const keys = configObject && Object.keys(configObject)
          keys?.length && keys.forEach(key => {
            list.push({
              nameCh: configObject[key],
              nameNg: key,
              value: this.options[key],
            });
          })

          if (this.selectIndex !== "") {
            // 编辑用户旅程
            this.updateJourneyItem(list)
          } else {
            // 新增用户旅程
            this.addJourneyItem(list)
          }

          this.resetJourneyConfig()
        }
      });
    },
    // 自定义校验
    otherValid() {
      if (this.form.triggerId === "8") {
        return this.numberCompare("consumptionMin", "consumptionMax");
      } else if (this.form.triggerId === "9") {
        // 按天数区间
        return this.numberCompare("dayMin", "dayMax");
      } else if (this.form.triggerId === "5") {
        // 按次数区间
        return this.numberCompare("frequencyMin", "frequencyMax");
      } else if ((this.form.triggerId === "6" || this.form.triggerId === "7") && this.selectIndex === "") {
        // 文章链接和指定日期不可重复
        const key = Object.keys(this.transToBack[this.form.triggerId])[0]
        const res = this.journeyFlowNodeList.filter(item =>
          item.scrmJourneyFlowNodeInfolist.filter(subitem => subitem.value === this.options[key]).length > 0)
        if (res.length > 0) {
          this.$message.error(this.errText[this.form.triggerId]);
          return false;
        }
      }
      return true
    },
    updateJourneyItem(list) {
      this.journeyFlowNodeList.splice(this.selectIndex, 1, {
        // 阶段名称
        flowNodeName: this.options.stageName,
        // 区间或链接配置
        scrmJourneyFlowNodeInfolist: list,
      });
    },
    addJourneyItem(list) {
      this.journeyFlowNodeList.splice(this.addIndex, 0, {
        flowNodeName: this.options.stageName,
        scrmJourneyFlowNodeInfolist: list,
      });
    },
    // 删除用户旅程阶段配置
    deleteoptions(index) {
      this.journeyFlowNodeList.splice(index, 1);
      this.resetJourneyConfig()
    },
    // 重置用户旅程阶段配置
    resetJourneyConfig() {
      if (this.addFlag) this.$refs["options"].resetFields();
      this.$nextTick(() => {
        this.addFlag = false
      })
      this.selectIndex = ""
    },
    // 页面确认
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let methods = this.type === "add" ? "post" : "put"
          let obj = {
            ...this.form,
            journeyFlowNodeList: this.journeyFlowNodeList,
          };
          this.pageLoading = true
          JourneyFlowInfo(obj, methods)
            .then((res) => {
              this.pageLoading = false
              if (res.code === 200) {
                // this.$message.success(res.data);
                if (this.type == 'add') {
                  this.$router.replace({
                    path: `editFollowStage`,
                    query: {
                      type: 'edit',
                      flowId: res.msg,
                    },
                  })
                }
                setTimeout(() => {
                  this.$router.push({
                    name: 'ClueDetail',
                    query: {
                      flowId: res.msg,
                    },
                  })
                }, 50);
                // this.goBack();
              }
            })
            .catch(err => {
              console.log(err)
              this.pageLoading = false
            })
        }
      });
    },
    // 返回
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}

.popover-text {
  font-size: 12px;
}

.toline {
  height: 32px;
  line-height: 32px;
  margin-top: 10px;
}

.options-btn {
  height: 96px;
  padding-top: 20px;
  box-sizing: border-box;
}

.options-flex {
  display: flex;
  justify-content: flex-start;
  padding: 0 20px;
  flex-wrap: nowrap;

  .options-list:last-child {

    .options-group .options-line {
      width: 40px;
    }
  }

  .options-list {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 16px;

    .options-item {
      position: relative;
      width: 136px;
      height: 82px;
      // background-color: #082aff;
      border-radius: 8px;

      .options-des {
        width: 126px;
        height: 28px;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 17px;
        margin: auto;
        padding: 6px 12px;
        box-sizing: border-box;
        overflow: hidden; //超出隐藏
        white-space: nowrap; //不折行
        text-overflow: ellipsis; //溢出显示省略号
      }

      .options-box {
        width: 126px;
        height: 48px;
        background: #ffffff;
        border-radius: 8px;
        margin: auto;
        font-size: 13px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #505050;
        line-height: 18px;
        padding: 15px 10px;
        box-sizing: border-box;
        overflow: hidden; //超出隐藏
        white-space: nowrap; //不折行
        text-overflow: ellipsis; //溢出显示省略号
      }

      .icon {
        width: 12px;
        height: 12px;
        position: absolute;
        top: 0px;
        right: 0px;
        z-index: 10;
      }
    }

    .options-group {
      position: relative;
      width: 80px;
      height: 82px;

      .options-line {
        position: absolute;
        top: 50%;
        left: 0;
        transform: translateY(-50%);
        width: 80px;
        height: 1px;
        border-bottom: 1px solid #fac8bc;
        background-color: #fac8bc;
      }

      .add-icon {
        position: absolute;
        top: 50%;
        left: 35px;
        transform: translateY(-50%);
        background-color: #fff;
        z-index: 9;
      }

      .delete-icon {
        position: absolute;
        top: 2px;
        left: -8px;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
